<?php

declare(strict_types=1);

namespace app\model;

use app\event\TemplateEditSuccess;
use think\facade\Cache;
use think\facade\Db;
use think\Model;
use think\model\concern\SoftDelete;

/**
 * 
 *
 * @mixin \think\Model
 * @property int $id
 * @property string $template_name 模版名称
 * @property string $pre_url 预览url
 * @property int $use_num 引用次数
 * @property int $status 状态 1启用  2禁用
 * @property string $created_at 创建时间
 * @property string $updated_at 更新时间
 * @property string $deleted_at 删除时间
 * @property string $template_img 预览图片
 * @property int $sort 排序
 * @property-read \app\model\TemplateService[] $service
 * @method static \think\db\Query onlyTrashed()
 * @method static \think\db\Query withTrashed()
 */
class Template extends CommonModel
{
    use SoftDelete;

    const STATUS_ACTIVE = 1;
    const STATUS_CLOSE = 2;



    public function service()
    {
        return $this->hasMany(TemplateService::class, 'template_id');
    }

    public function showList($params)
    {
        $where = $this->setWhere($params);
        $paginate = [
            'page' => $params['page'] ?? 1,
            'list_rows' => $params['list_rows'] ?? 10,
        ];
        $list = self::where($where)
            ->with(['service' => function ($query) {
                $query->field('serv_type,template_id');
            }])
            ->order('sort desc, id asc')
            ->paginate($paginate)->toArray();
        $types = PRODUCT_SERV_TYPE;
        foreach ($list['data'] as $kk => $vv) {
            foreach ($types as $nk => $nv) {
                $list['data'][$kk]['serv_types'][$nk] = false;
            }
            foreach ($vv['service'] as $k => $v) {
                $list['data'][$kk]['serv_types'][$v['serv_type']] = true;
            }
        }
        return success('操作成功', $list);
    }

    /**
     * 新增模板
     * @params array $params
     * @returns string
     */
    public function addTemplate(array $params)
    {
        //判断该木板是否已存在
        $info = self::where('template_name', $params['template_name'])->whereOr('pre_url', $params['pre_url'])->find();
        if ($info) {
            return fail('模板名称或者模板路径已存在');
        }
        $ids = [];
        if (!empty($params['serv_types'])) {
            foreach ($params['serv_types'] as $nk => $nv) {
                if ($nv) {
                    $ids[] = $nk;
                }
            }
        }
        Db::startTrans();
        try {
            $template = self::create($params);
            if (!empty($ids)) {
                $save = $saveAll = [];
                foreach ($ids as $v) {
                    $save['template_id'] = $template->id;
                    $save['serv_type'] = $v;
                    $saveAll[] = $save;
                }
                if (!empty($saveAll)) {
                    TemplateService::where('template_id', $template->id)->delete();
                    $servce = new TemplateService();
                    $servce->saveAll($saveAll);
                }
            }
            Db::commit();
            //生成缓存
            /**
             * @var Template $template
             */
            event(new TemplateEditSuccess($template));

            return success('新增模板成功');
        } catch (\Exception $e) {
            Db::rollback();
            return fail('新增模板失败: ' . $e->getMessage());
        }
    }

    /**
     *  修改状态
     */
    public function optionStatus($params)
    {
        $info = self::where('id', $params['id'])->find();
        if (empty($params['id'])) {
            return fail('该模板不存在');
        }
        $info->status = $params['status'];
        $info->save();

        return success('保存成功！');
    }

    /**
     *  编辑模版.
     */
    public function editTemplate($params)
    {
        $info = self::where('id', $params['id'])->find();
        if (empty($params['id'])) {
            return fail('该模板不存在');
        }
        $ids = [];
        if (!empty($params['serv_types'])) {
            foreach ($params['serv_types'] as $nk => $nv) {
                if ($nv) {
                    $ids[] = $nk;
                }
            }
        }
        $info->template_name = $params['template_name'];
        $info->sort = $params['sort'];
        $info->status = $params['status'];
        $info->pre_url = $params['pre_url'];
        if (isset($params['template_img']) && !empty($params['template_img'])) {
            $info->template_img = $params['template_img'];
        }
        $info->save();
        if (!empty($ids)) {
            $save = $saveAll = [];
            foreach ($ids as $k => $v) {
                $save['template_id'] = $info->id;
                $save['serv_type'] = $v;
                $saveAll[] = $save;
            }
            if (!empty($saveAll)) {
                TemplateService::where('template_id', $info->id)->delete();
                $servce = new TemplateService();
                $servce->saveAll($saveAll);
            }
        }
        //保存成功后，重新生成缓存
        /**
         * @var Template $info
         */
        event(new TemplateEditSuccess($info));

        return success('保存成功！');
    }

    //设置条件
    public function setWhere($params)
    {
        $where = [];
        if (!empty($params['template_name'])) {
            $where[] = ['template_name', 'like', '%' . $params['template_name'] . '%'];
        }
        if (!empty($params['status'])) {
            $where[] = ['status', '=', $params['status']];
        }

        return $where;
    }

    //根据模板查询服务
    public function getServType($template_url)
    {
        $serv_type = [];
        if (empty($template_url)) {
            return $serv_type;
        }
        $list = self::query()->where('pre_url', $template_url)
            ->where('status', self::STATUS_ACTIVE)
            ->with(['service' => function($query) {
                $query->field('template_id, serv_type');
        }])->find()->toArray();

        if (!empty($list['service'])) {
            $serv_type = array_column($list['service'], 'serv_type');
        }
        return $serv_type;
    }

}
